import {login, logout, getInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/common/auth'
import {Message, MessageBox} from 'element-ui'

const user = {
  state: {
    token: getToken(),
    username: '',
    name: '',
    telphone: '',
    avatar: '',
    platformType: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_TELPHONE: (state, telphone) => {
      state.telphone = telphone
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PLATFORM_TYPE: (state, platformType) => {
      state.platformType = platformType
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({commit}, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(userInfo.t, username, userInfo.password, (res) => {
          setToken(res)
          commit('SET_TOKEN', res)
          resolve()
        }, (msg) => {
          Message({
            message: msg,
            type: 'error',
            duration: 5 * 1000
          })
          reject()
        }, () => {
        })
      })
    },

    // 获取用户信息
    GetInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo(state.token, (res) => {
          const roles = res.user.roleCode
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles)
            commit('SET_NAME', res.user.username)
            if(res.user.avatar){
              if('https'.indexOf(res.user.avatar)>-1){
                commit('SET_AVATAR', res.user.avatar)
              }else{
                commit('SET_AVATAR', process.env.IMG_BASE_URL+res.user.avatar)
              }
            }
            commit('SET_PLATFORM_TYPE', res.user.platformType)
            commit('SET_USERNAME', res.user.name)
            commit('SET_TELPHONE', res.user.telphone)
            resolve(res)
          } else {
            logout(state.token, (res) => {
              commit('SET_TOKEN', '')
              commit('SET_ROLES', [])
              removeToken()
            }, () => {
            })
            reject('账号无法使用')
          }
        }, () => {
        })
      })
    },

    // 登出
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token, (res) => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }, () => {
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
